package com.xatz.scanner

import android.annotation.SuppressLint
import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.xatz.scanner.bean.OutDatasBean
import com.xatz.scanner.databinding.FragmentResultPageBinding
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import timber.log.Timber
import java.io.StringReader
import java.math.BigDecimal

/**
 * author: tdq
 * date: 2021/7/20
 * description: 结果页
 */
class ResultPageFragment : Fragment() {

    private lateinit var mBinding: FragmentResultPageBinding

    private lateinit var mAdapter: MyAdapter

    private var totalWgt = 0.0

    private var count = 0

    private var mActivity: SalesActivity? = null

    private var type = ""

    private val mService by lazy {
        ScannerRetrofitClient().getService(
            ScannerService::class.java,
            ScannerService.baseUrl
        )
    }

    private var mDatas: MutableList<OutDatasBean> = mutableListOf()

    private var outDatasBean: OutDatasBean? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        mBinding = FragmentResultPageBinding.inflate(inflater, container, false)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        mActivity = requireActivity() as SalesActivity
        mAdapter = MyAdapter(mDatas)
        mBinding.rvDetails.adapter = mAdapter
        mBinding.btnDel.setOnClickListener {
            val activity = requireActivity() as SalesActivity
            val delText = mBinding.tvOrderNum.text.trim().toString()
            if (delText.isBlank()) {
                activity.toast("请输入或扫描件次号！")
                return@setOnClickListener
            }
            activity.repeatScannerHandle(mBinding.tvOrderNum.text.trim().toString())
        }
    }

    fun onScannerResult(soCode: String) {
        requireActivity().runOnUiThread {
            getOutDatas(soCode)
        }

    }

    fun setOrderNumber(orderNum: String, carNum: String) {
        requireActivity().runOnUiThread {
            mBinding.tvOrder.text = orderNum
            mBinding.tvCarNum.text = carNum
        }
        getOutDatas(orderNum)
    }

    fun onScannerDelResult(soCode: String) {
        getOutDatas(soCode)
    }

    fun clearData() {
        mBinding.tvOrder.text = ""
        mBinding.tvCarNum.text = ""
        mBinding.tvOrderNum.text = Editable.Factory.getInstance().newEditable("")
        mBinding.tvWeight.text = ""
        mBinding.tvCount.text = ""
        totalWgt = 0.0
        count = 0
        mDatas.clear()
        mAdapter.notifyDataSetChanged()
    }

    fun setBarCodeShow(barCode: String) {
        requireActivity().runOnUiThread {
            mBinding.tvOrderNum.text = Editable.Factory.getInstance().newEditable(barCode)
        }
    }

    private fun getOutDatas(code: String) {
        mService.getOutDatas(code).enqueue(object : Callback<String> {
            @SuppressLint("SetTextI18n")
            override fun onResponse(call: Call<String>, response: Response<String>) {
                if (response.isSuccessful) {
                    response.body()?.let { tabStr ->
                        parseXMLWithPull(tabStr)
                        mAdapter.notifyDataSetChanged()
                        count = mDatas.size
                        mBinding.tvCount.text = count.toString()
                        totalWgt = 0.0
                        mDatas.forEach { totalWgt += it.wgt.toDouble() }
                        val value = BigDecimal(totalWgt).setScale(3, BigDecimal.ROUND_HALF_UP)
                        mBinding.tvWeight.text = value.toString()
                        mBinding.tvCount.text = mDatas.size.toString()
                        mActivity?.setCountAndWeight(mDatas.size,value.toDouble())
                        if(mDatas.isNotEmpty()){
                            type = mDatas[0].guige
                        }
                    }
                }
            }

            override fun onFailure(call: Call<String>, t: Throwable) {
            }

        })
    }

    private fun parseXMLWithPull(xmlData: String) {
        mDatas.clear()
        try {
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            while (eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when (eventType) {
                    XmlPullParser.START_DOCUMENT -> {
                    }
                    XmlPullParser.START_TAG -> {
                        when (nodeName) {
                            "Table" -> {
                                outDatasBean = OutDatasBean("", "", "")
                            }
                            "C_ROLL_PIECE" -> outDatasBean?.piece = xmlPullParser.nextText()
                            "GUIGE" -> outDatasBean?.guige = xmlPullParser.nextText()
                            "N_WGT" -> outDatasBean?.wgt = xmlPullParser.nextText()
                        }
                    }
                    XmlPullParser.END_TAG -> {
                        if ("Table" == xmlPullParser.name) {
                            outDatasBean?.let { mDatas.add(it) }
                            outDatasBean = null
                        }
                    }
                }
                eventType = xmlPullParser.next()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }


}

class MyAdapter(private val mList: MutableList<OutDatasBean>) :
    RecyclerView.Adapter<MyViewHolder>() {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): MyViewHolder {
        return MyViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.item_details, parent, false)
        )
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        try {
            holder.tvNum?.text = mList[position].piece
            holder.tvType?.text = mList[position].guige
            holder.tvWeight?.text = mList[position].wgt
        } catch (e: Exception) {
            Timber.e(e)
        }

    }

    override fun getItemCount(): Int {
        return mList.size
    }
}

class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    var tvNum: TextView? = null
    var tvType: TextView? = null
    var tvWeight: TextView? = null

    init {
        tvNum = itemView.findViewById(R.id.tvNum)
        tvType = itemView.findViewById(R.id.tvType)
        tvWeight = itemView.findViewById(R.id.tvWeight)
    }
}